package com.example.contextcube;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.fragment.app.Fragment;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;

import com.example.contextcube.util.FontSizeManager;
import com.example.contextcube.util.LocaleManager;
import com.example.contextcube.util.SharedPrefsUtil;

public class SettingsFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_settings, container, false);
        
        // 加载偏好设置Fragment
        if (savedInstanceState == null) {
            getChildFragmentManager()
                    .beginTransaction()
                    .replace(R.id.settings_container, new PreferenceSettingsFragment())
                    .commit();
        }
        
        return view;
    }
    
    // 内部类，用于显示偏好设置
    public static class PreferenceSettingsFragment extends PreferenceFragmentCompat 
            implements SharedPreferences.OnSharedPreferenceChangeListener {
        
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.settings_preferences, rootKey);
            
            // 初始化字体大小偏好设置
            ListPreference fontSizePref = findPreference("font_size");
            if (fontSizePref != null) {
                fontSizePref.setOnPreferenceChangeListener((preference, newValue) -> {
                    // 显示确认对话框
                    showFontSizeConfirmDialog((String) newValue);
                    return false; // 暂不修改值，等用户确认
                });
            }
            
            // 初始化语言偏好设置
            ListPreference languagePref = findPreference("language");
            if (languagePref != null) {
                languagePref.setOnPreferenceChangeListener((preference, newValue) -> {
                    // 显示确认对话框
                    showLanguageConfirmDialog((String) newValue);
                    return false; // 暂不修改值，等用户确认
                });
            }
            
            // 初始化退出登录偏好设置
            Preference logoutPref = findPreference("logout");
            if (logoutPref != null) {
                logoutPref.setOnPreferenceClickListener(preference -> {
                    showLogoutConfirmDialog();
                    return true;
                });
            }
        }
        
        @Override
        public void onResume() {
            super.onResume();
            // 注册监听器
            PreferenceManager.getDefaultSharedPreferences(requireContext())
                    .registerOnSharedPreferenceChangeListener(this);
        }
        
        @Override
        public void onPause() {
            super.onPause();
            // 取消注册监听器
            PreferenceManager.getDefaultSharedPreferences(requireContext())
                    .unregisterOnSharedPreferenceChangeListener(this);
        }
        
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            // 监听夜间模式设置变化
            if ("dark_mode".equals(key)) {
                boolean isDarkMode = sharedPreferences.getBoolean(key, false);
                applyDarkMode(isDarkMode);
            }
            // 监听字体大小设置变化
            else if ("font_size".equals(key)) {
                String fontSize = sharedPreferences.getString(key, "medium");
                applyFontSize(fontSize);
            }
            // 监听语言设置变化
            else if ("language".equals(key)) {
                String language = sharedPreferences.getString(key, LocaleManager.LANGUAGE_CHINESE);
                applyLanguage(language);
            }
        }
        
        /**
         * 显示退出登录确认对话框
         */
        private void showLogoutConfirmDialog() {
            String title = getString(R.string.logout);
            String message = getString(R.string.logout_confirm);
            
            new AlertDialog.Builder(requireContext())
                    .setTitle(title)
                    .setMessage(message)
                    .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                        logout();
                    })
                    .setNegativeButton(android.R.string.cancel, null)
                    .show();
        }
        
        /**
         * 执行退出登录操作
         */
        private void logout() {
            // 清除登录状态
            SharedPrefsUtil.clearLoginState(requireContext());
            
            // 返回登录页面
            Intent intent = new Intent(requireContext(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            requireActivity().finish();
        }
        
        /**
         * 显示字体大小确认对话框
         * @param newSize 新的字体大小值
         */
        private void showFontSizeConfirmDialog(String newSize) {
            new AlertDialog.Builder(requireContext())
                    .setTitle(R.string.font_size)
                    .setMessage(R.string.font_size_change_confirm)
                    .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                        // 更新偏好设置
                        SharedPreferences.Editor editor = PreferenceManager
                                .getDefaultSharedPreferences(requireContext()).edit();
                        editor.putString("font_size", newSize);
                        editor.apply();
                    })
                    .setNegativeButton(android.R.string.cancel, null)
                    .show();
        }
        
        /**
         * 显示语言确认对话框
         * @param newLanguage 新的语言值
         */
        private void showLanguageConfirmDialog(String newLanguage) {
            new AlertDialog.Builder(requireContext())
                    .setTitle(R.string.language)
                    .setMessage(R.string.language_change_confirm)
                    .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                        // 更新偏好设置
                        SharedPreferences.Editor editor = PreferenceManager
                                .getDefaultSharedPreferences(requireContext()).edit();
                        editor.putString("language", newLanguage);
                        editor.apply();
                    })
                    .setNegativeButton(android.R.string.cancel, null)
                    .show();
        }
        
        /**
         * 应用夜间模式设置
         * @param isDarkMode 是否启用夜间模式
         */
        private void applyDarkMode(boolean isDarkMode) {
            int nightMode = isDarkMode ? 
                    AppCompatDelegate.MODE_NIGHT_YES : 
                    AppCompatDelegate.MODE_NIGHT_NO;
            
            // 应用夜间模式设置
            AppCompatDelegate.setDefaultNightMode(nightMode);
            
            // 重新创建Activity以应用新主题
            AppCompatActivity activity = (AppCompatActivity) requireActivity();
            Intent intent = activity.getIntent();
            activity.finish();
            startActivity(intent);
            activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        }
        
        /**
         * 应用字体大小设置
         * @param fontSize 字体大小设置值
         */
        private void applyFontSize(String fontSize) {
            // 应用字体大小设置
            FontSizeManager.getInstance().applyFontSize(requireContext(), fontSize);
            
            // 重新创建Activity以应用新设置
            restartActivity();
        }
        
        /**
         * 应用语言设置
         * @param language 语言代码
         */
        private void applyLanguage(String language) {
            // 应用语言设置
            LocaleManager.getInstance().setLocale(requireContext(), language);
            
            // 重新创建Activity以应用新设置
            restartActivity();
        }
        
        /**
         * 重启Activity以应用新设置
         */
        private void restartActivity() {
            AppCompatActivity activity = (AppCompatActivity) requireActivity();
            Intent intent = activity.getIntent();
            activity.finish();
            startActivity(intent);
            activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        }
    }
}